<?php

class Router
{
	public        $rootDir;
	public        $pathInfo;
	public        $path;
	static public $params = [];

	static public $paths = [];

	public function __construct($pathInfo)
	{
//		$this->pathInfo = $pathInfo;
//		$this->rootDir  = \lib\Root::Config('http_server', 'root');
//		$this->path     = ROOT_DIR . DIRECTORY_SEPARATOR . $this->rootDir . DIRECTORY_SEPARATOR . $this->path;
	}

	/**
	 * @param $path
	 * @param array $handler [
	 *      namespace
	 *      controller
	 *      action
	 *      params
	 *      ...
	 *      ...
	 * ]
	 */
	static function addRoute($path, $handler = [])
	{
		self::$paths[$path] = $handler;
	}

	public function add($path, $handler = [])
	{
		self::addRoute($path, $handler);
		return $this;
	}

	static public function getController($request)
	{

		$path   = $request->path_info;
		$method = strtolower($request->method);

		if (!$method) {
			return false;
		}

		if (isset(self::$paths[$method][$path])) {
			return self::$paths[$method][$path];
		}

		$pathArray = explode('/', $path);
		unset($pathArray[0]);

		if(!@self::$paths[$method] || count(self::$paths[$method]) < 1){
			return false;
		}

		foreach (self::$paths[$method] as $k => $v) {
			$keyPath = explode('/', $k);
			unset($keyPath[0]);


			if (count($keyPath) != count($pathArray)) {
				continue;
			}

			if ($con = self::pathMatch($k, $keyPath, $pathArray,$method)) {
				return $con;
			}
			else {
				continue;
			}

		}

		return false;
	}

	static public function pathMatch($k, $keyPath, $pathArray,$method)
	{
		foreach ($keyPath as $key => $path) {
			if ($keyPath[$key] != $pathArray[$key]) {
				if (preg_match_all('/{(.*?)}/', $path, $matches)) {
					self::$params[$matches[1][0]] = urldecode($pathArray[$key]);
				}
				else {
					return false;
				}
			}
		}

		return self::$paths[$method][$k];
	}


}